/*
Copyright (c) 2013 Aaron Mark Brown http://aaronmarkbrown.com

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.


*/

function JSound() {

}

JSound.sounds = [];
JSound.context;
JSound.initialized = false;
JSound.webAudioAPI = (('webkitAudioContext' in window || 'AudioContext' in window) ? true : false);
JSound.soundFormat = (navigator.userAgent.match(/(iPad|iPhone|iPod|Safari|MSIE)/g) ? 'mp3' : 'ogg');
JSound.base64 = false;
JSound.muted = false;

JSound.soundIsPlaying = function(soundName)
{
	if(JSound.webAudioAPI){
		if(soundName in JSound.sounds){
			if(!JSound.sounds[soundName].source){
				return false;
			}
			if(JSound.sounds[soundName].source.buffer){
				return true;
			}
		}
	} else {
		if(soundName in JSound.sounds){
			return !JSound.sounds[soundName].audioElement.paused;
		}
	}
	return false;
}

JSound.soundExists = function(soundName)
{
	if(soundName in JSound.sounds){
		if(JSound.sounds[soundName].source)
			return true;
	}
	return false;
}

// This is only necessary for iOS and should be called from a touch event
JSound.initSounds = function(){
	for(var soundName in JSound.sounds)
	{
		if(soundName == '__class__') continue;
		if(!JSound.sounds[soundName].source){	
			JSound.playSound(soundName);
			JSound.stopSound(soundName);
		}
	}
	JSound.initialized = true;
}

JSound.addSound = function(soundName, context, url, base64Sound) {


	if(JSound.sounds[soundName]) return;

	if(!context) context = 'default';
	
	JSound.sounds[soundName] = {};
	JSound.sounds[soundName].context = JSound.getContext(context);
	JSound.sounds[soundName].base64Sound = base64Sound;
	JSound.sounds[soundName].url = url;
	JSound.sounds[soundName].arrayBuffer = null;
	
	if(!JSound.webAudioAPI){
		JSound.sounds[soundName].audioElement = document.createElement("audio");
		JSound.sounds[soundName].audioElement.id = soundName;
		JSound.sounds[soundName].audioElement.autostart = false;
		if(JSound.base64)
			JSound.sounds[soundName].audioElement.src = (JSound.soundFormat == 'mp3') ? "data:audio/mpeg;base64,"+JSound.sounds[soundName].base64Sound : "data:audio/ogg;base64,"+JSound.sounds[soundName].base64Sound;
		else
			JSound.sounds[soundName].audioElement.src = url;
		JSound.sounds[soundName].audioElement.oncanplaythrough = function(e)
		{
			JSound.sounds[e.target.id].canPlayThrough = true;
			if(JSound.sounds[e.target.id].playOnLoad){
				JSound.sounds[e.target.id].playOnLoad = false;
				JSound.playSound(e.target.id, JSound.sounds[e.target.id].loopOnLoad);
			}
		}
		JSound.sounds[soundName].audioElement.load();
	}
}

JSound.getContext = function(contextName) {
	if(JSound.webAudioAPI){
		if(!JSound.context){
			try {
				JSound.context = new webkitAudioContext() || AudioContext();
			} catch(e){
				try {
					JSound.context = new AudioContext();
				} catch(e){
					alert(e);
				}
			}
		}
		return JSound.context;
	}
}

JSound.toggleMute = function() {
	JSound.muted = !JSound.muted;
	if(JSound.webAudioAPI){
		if(!JSound.context){
			return;
		}
		JSound.context.gainNode.gain.value = JSound.muted ? 0 : 1;
	} else {
		for(var soundName in JSound.sounds){
			if(JSound.sounds[soundName].audioElement)
				JSound.sounds[soundName].audioElement.volume = JSound.muted ? 0 : 1;
		}
	}
}

JSound.loadSound = function(soundName, url, playOnLoad, loopOnLoad) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'arraybuffer';
  xhr.onload = function(e) {
    JSound.sounds[soundName].arrayBuffer = this.response;
    if(playOnLoad){
    	JSound.playSound(soundName, loopOnLoad);
    }
  };
  xhr.send();
}

JSound.playSound = function(soundName, loop) {
	
	var thisSound = JSound.sounds[soundName];
	
	if(!thisSound){
		console.log('JSound.playSound : Sound not found : '+soundName);
		return;
	}
	
	if(JSound.webAudioAPI){
	
		if(!thisSound.context) return;

		if(!thisSound.source || !thisSound.paused){
		
			thisSound.source = thisSound.context.createBufferSource();

			if(JSound.base64){
				var arrayBuffer = Base64Binary.decodeArrayBuffer(thisSound.base64Sound);
				thisSound.context.decodeAudioData(arrayBuffer, function(audioData) {
					try {
						thisSound.arrayBuffer = thisSound.source.buffer = audioData;
					} catch(e) {}
				});
			} else if(!thisSound.arrayBuffer){
				JSound.loadSound(soundName, thisSound.url, true, loop);
				return;
			} else {
				thisSound.context.decodeAudioData(thisSound.arrayBuffer, function(buffer) {
					thisSound.source.buffer = buffer;
				  }, function(e) {
					console.log('Error decoding file', e);
				}); 
			}
		}
	
		thisSound.source.loop = Boolean(loop);
		
		if(!thisSound.context.gainNode){
			try {
				thisSound.context.gainNode = thisSound.context.createGainNode();
			} catch(e) {
				thisSound.context.gainNode = thisSound.context.createGain();
			}
		}

		thisSound.source.connect(thisSound.context.gainNode); 
		thisSound.context.gainNode.connect(thisSound.context.destination);
	
		try {
			thisSound.source.noteOn(0);
		} catch(e){
			thisSound.source.start(0);
		}
		
		
	} else {
		if(thisSound.canPlayThrough){
			if(thisSound.timeout){
				clearTimeout(thisSound.timeout);
			}
			if(loop){
				thisSound.timeout = setTimeout(function(){
					JSound.playSound(soundName, loop);
				}, thisSound.audioElement.duration*1000);
			}
			thisSound.audioElement.currentTime = 0;
			thisSound.audioElement.play();
		} else {
			thisSound.playOnLoad = true;
			thisSound.loopOnLoad = loop;
		}
	}
	
	thisSound.paused = false;
	
};


JSound.pauseSound = function (soundName) {
	
	if(!(soundName in JSound.sounds)){
		console.log('JSound.pauseSound : Sound not found : '+soundName);
		return;	
	}
	
	if(JSound.webAudioAPI){
		if(JSound.sounds[soundName].source)
			JSound.sounds[soundName].source.disconnect();
	} else {
		if(JSound.sounds[soundName].timeout){
			clearTimeout(JSound.sounds[soundName].timeout);
		}
		JSound.sounds[soundName].audioElement.pause();
	}
	
	JSound.sounds[soundName].paused = true;
};

JSound.stopSound = function (soundName) {
	
	if(!(soundName in JSound.sounds)){
		console.log('JSound.stopSound : Sound not found : '+soundName);
		return;	
	}
	
	JSound.pauseSound(soundName);
	
	if(JSound.webAudioAPI){
		JSound.sounds[soundName].source = null;
	} else {
		JSound.sounds[soundName].audioElement.currentTime = 0;
	}
};

JSound.attachSliderToContext = function(slider, context){
	
	if(!(slider instanceof HTMLInputElement)){
		console.log('JSound.attachSliderToContext : Invalid slider: '+slider);
		return;	
	}
		
	if(!(context in JSound.contexts)){	
		if (JSound.webAudioAPI) {
			JSound.contexts[context] = {};
			JSound.contexts[context]['context'] = new webkitAudioContext() || AudioContext();
		}
	}
	
	if(JSound.webAudioAPI){
		JSound.contexts[context].gainNode = JSound.contexts[context]['context'].createGainNode();
		JSound.contexts[context].slider = slider;
		
		JSound.contexts[context].slider.addEventListener('change', JSound.updateVolume);
	}
}
	
JSound.updateVolume = function(e){
	
	if(JSound.context.slider == e.target){
		JSound.context.gainNode.gain.value = JSound.context.slider.value;
	}
}